package org.duang.logs.db.mongodb;

import org.duang.logs.db.ILogDBFactory;
import org.duang.logs.db.ToolUtils;

import com.mongodb.DB;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;
import com.mongodb.WriteResult;

public class MongodbLogBackDBFactory implements ILogDBFactory<DBObject> {

	private static MongodbLogBackDBFactory dbFactory;
	private static Mongo mongo;
	private static DB mongoDB;
	
	public static MongodbLogBackDBFactory init() {
		if(null == dbFactory){
			dbFactory = new MongodbLogBackDBFactory();
		}
		return dbFactory;
	}
	
	@SuppressWarnings("deprecation")
	public MongodbLogBackDBFactory() {
		if(mongo == null){
			mongoDB = getMongoDB();
		} else {
			mongoDB = mongo.getDB(ToolUtils.getIndexName());
		}
	}
	
	@SuppressWarnings({ "resource", "deprecation" })
	private static DB getMongoDB() {
		ServerAddress sa = new ServerAddress(ToolUtils.getMongoHost(), ToolUtils.getMongoPort());
		mongoDB = new MongoClient(sa).getDB(ToolUtils.getIndexName());
		System.out.println("########logback for mongodb:  " +  sa.getHost() + ":"+ sa.getPort() +",  dbname: " + ToolUtils.getIndexName() + ",  controller: " + ToolUtils.getTypeName());
		return mongoDB;
	}

	@Override
	public boolean insert(DBObject dbo) {
		WriteResult wr = mongoDB.getCollection(ToolUtils.getTypeName()).insert(dbo);
		if (wr.getN() >= 0){
			return true;
		} else { 
			throw new RuntimeException(wr.toString());
		}
	}
}
